package org.example;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


//自定义的java-spi   只需根据约定好的资源文件中找到抽象类对于的实现类 然后加载即可
public class MyServiceLoader {

    public static <T> List<T> load(Class<T> serviceInterface) {
        List<T> result = new ArrayList<>();

        String resourceFile = "META-INF/services/" + serviceInterface.getName();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        try (InputStream is = classLoader.getResourceAsStream(resourceFile)) {


            if (is == null) {
                throw new RuntimeException("找不到 SPI 配置文件: " + resourceFile);
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty() || line.startsWith("#")) continue;

                // 动态加载类
                Class<?> implClass = Class.forName(line, true, classLoader);

                // 校验是否实现了接口
                if (!serviceInterface.isAssignableFrom(implClass)) {
                    throw new RuntimeException("类 " + line + " 没有实现接口 " + serviceInterface.getName());
                }

                // 创建实例
                T instance = serviceInterface.cast(implClass.getDeclaredConstructor().newInstance());
                result.add(instance);
            }




        } catch (Exception e) {
            throw new RuntimeException("SPI 加载失败: " + e.getMessage(), e);
        }

        return result;
    }
}
